package Util;

import domain.ZhejiangGDP;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class ReadZhejiangGDP {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        ArrayList<List> a = new ArrayList();
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String temp = null;
            int line = 1;
            SqlSession session = sqlSessionFactory.openSession();
            dao.ZhejiangGDPMapper operation = session.getMapper(dao.ZhejiangGDPMapper.class);
            while ((temp = reader.readLine()) != null) {
                String s[] = temp.split("\t");
                ZhejiangGDP zhgdp = new ZhejiangGDP();
                zhgdp.setId(0);
                zhgdp.setCity("金华");
                zhgdp.setType(s[0].trim());
                DecimalFormat df = new DecimalFormat("#.00");
                zhgdp.setValue(Double.parseDouble(df.format(Double.parseDouble(s[1])/10000)));
                zhgdp.setYear(2016);
                operation.insert(zhgdp);
                session.commit();
            }
            session.close();
        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

    }

    public static void main(String[] args) {
        String fileName = "C:\\Users\\admin\\Desktop\\a.txt";
        ReadZhejiangGDP.readFileByLines(fileName);
    }
}
